package com.maxd.controller.selfAliPay;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.maxd.adapter.IgnoreSecurity;
import com.maxd.constants.AliPayConstants;
import com.maxd.constants.AliPayNotifyParamConstants;
import com.maxd.error.Result;
import com.maxd.error.ResultUtil;
import com.maxd.model.*;
import com.maxd.respository.common.CommonRepository;
import com.maxd.respository.selfGoods.GoodsJpaRepository;
import com.maxd.respository.selfGoodsSku.SelfGoodsSkuJpaRepository;
import com.maxd.respository.selfOrder.OrdersJpaRepository;
import com.maxd.respository.selfOrderRemind.SelfOrdersRemindJpaRepository;
import com.maxd.respository.userinfo.UserRepository;
import com.maxd.service.jifen.IJiFenService;
import com.maxd.service.selfGoods.GoodsService;
import com.maxd.service.selfGoodsVirtual.SelfGoodsVirtualService;
import com.maxd.service.selfOrder.OrdersService;
import com.maxd.service.userinfo.IUserService;
import com.maxd.utils.AliPayOrderUtil;
import com.maxd.utils.AmountCalUtils;
import com.maxd.utils.Config;
import com.maxd.utils.DateUtil;
import com.yungouos.pay.alipay.AliPay;
import com.yungouos.pay.entity.AliPayH5Biz;
import com.yungouos.pay.util.PaySignUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.*;

@Api(value="自营商城支付宝支付",tags={"自营商城支付宝支付"})
@Slf4j
@RestController
@RequestMapping("/aliPay")
public class SelfAliPayController {

    @Autowired
    private CommonRepository commonRepository;
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private OrdersJpaRepository ordersJpaRepository;
    @Autowired
    private SelfGoodsVirtualService selfGoodsVirtualService;
    @Autowired
    private IUserService userService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private GoodsJpaRepository goodsJpaRepository;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private IJiFenService jiFenService;
    @Autowired
    private SelfOrdersRemindJpaRepository selfOrdersRemindJpaRepository;
    @Autowired
    private SelfGoodsSkuJpaRepository selfGoodsSkuJpaRepository;


    /**
     * 创建线程池处理业务逻辑
     */
    private ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().build();
    private ExecutorService singleThreadPool = new ThreadPoolExecutor(30, 100,
            0L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());

    /**
     * 支付宝网页支付
     *
     * @param response
     * @throws IOException
     */
    @RequestMapping("/payment")
    public void aliPay(HttpServletResponse response) throws IOException {

        AlipayClient alipayClient = new DefaultAlipayClient(AliPayConstants.REQUEST_URL,
                commonRepository.findOne(63).getValue(), commonRepository.findOne(65).getValue(), AliPayConstants.FORMAT,
                AliPayConstants.CHARSET, commonRepository.findOne(64).getValue(), AliPayConstants.SIGNTYPE);
        //封装请求参数
        AlipayTradeWapPayRequest aliPayRequest = new AlipayTradeWapPayRequest();
        AliPayParamModel aliPayParamModel = new AliPayParamModel();
        aliPayParamModel.setOut_trade_no("2018120514559696060");
        aliPayParamModel.setSubject("支付测试");
        aliPayParamModel.setTotal_amount("0.01");
        aliPayParamModel.setProduct_code(AliPayConstants.PRODUCT_CODE);
        // TODO 同步处理业务-涉及到商户自定义页面跳转
        aliPayRequest.setReturnUrl("http://ip:port/api/aliPay/return");
        // TODO 异步处理业务-修改订单状态、校验签名是否正确
        aliPayRequest.setNotifyUrl("http://ip:port/api/aliPay/notify");
        aliPayRequest.setBizContent(JSON.toJSONString(aliPayParamModel));
        try {
            // 调用SDK生成表单
            String form = alipayClient.pageExecute(aliPayRequest).getBody();
            response.setContentType("text/html;charset=" + AliPayConstants.CHARSET);
            response.getWriter().write(form);
            response.getWriter().flush();
            response.getWriter().close();
        } catch (AlipayApiException e) {
            log.info("支付宝支付异常，异常信息为:" + e.getErrMsg());
            e.printStackTrace();
        }
    }

    /**
     * 支付宝异步通知地址
     * @param request
     * @return
     */
    @RequestMapping("notify")
    @Transactional(rollbackFor = Exception.class)
    public void returnUrl(HttpServletRequest request, HttpServletResponse response) {
        Map<String, String> params = AliPayOrderUtil.convertRequestParamsToMap(request);
        String result = "";
        //调用SDK验证签名
        boolean signVerified = false;
        try {
            signVerified = AlipaySignature.rsaCheckV1(params, commonRepository.findOne(64).getValue(),
                    AliPayConstants.CHARSET, AliPayConstants.SIGNTYPE);
        } catch (AlipayApiException e) {
            log.info("支付宝回调验签异常：" + e.getMessage());
            e.printStackTrace();
        }
        if (signVerified) {
            this.check(params);
            singleThreadPool.execute(() -> {
                AliPayNotifyParamConstants param = AliPayOrderUtil.buildAliPayNotifyParam(params);
                String tradeStatus = param.getTradeStatus();
                //支付成功
                if (tradeStatus.equalsIgnoreCase(AliPayConstants.TRADE_SUCCESS)) {
                    // TODO 处理业务逻辑
                    String outTradeNo = params.get("out_trade_no");
                    //支付成功，处理业务
                    Orders orders = ordersService.findByOrderNum(outTradeNo);
                    if (orders.getStatus() == 1){
                        orders.setPayWay(2); //支付方式为2支付宝
                        orders.setStatus(2); //2已付款
                        orders.setPayTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); //设置支付时间
                        ordersService.updateBody(orders);
                    }
                }
            });
            result = "success";
        } else {
            result = "failure";
        }
        try {
            BufferedOutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            outputStream.write(result.getBytes());
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            log.info("支付宝返回异常，异常信息为：" + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 校验支付宝支付返回的订单信息是否正确
     *
     * @param params
     */
    private void check(Map<String, String> params) {
        for (String key : params.keySet()){
            log.info("key="+key+";  value="+params.get(key));
        }
        // TODO 判断支付订单号是否是同一个
        String outTradeNo = params.get("out_trade_no");
        // 订单支付金额是否正确
        BigDecimal totalAmount = new BigDecimal(params.get("total_amount"));
//        Assert.isTrue(!totalAmount.equals(new BigDecimal(0.2)), "支付金额错误");
        // 判断支付的商户信息是否一致
        Assert.isTrue(params.get("app_id").equals(commonRepository.findOne(63).getValue()), "支付的商户信息不正确");
    }

    @IgnoreSecurity
    @RequestMapping("/notifyApp")
    @Transactional(rollbackFor = Exception.class)
    public void notifyApp(HttpServletRequest request, HttpServletResponse response){
        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        //切记alipaypublickey是支付宝的公钥，请去open.alipay.com对应应用下查看。
        //boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
        try {
            log.info("回调成功！！！");
            boolean flag = AlipaySignature.rsaCheckV1(params, commonRepository.findOne(64).getValue(), AliPayConstants.CHARSET,"RSA2");
            log.info(flag+"回调验证信息");
            if(flag){
                String tradeStatus = params.get("trade_status");
                if("TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus)){
                    String outTradeNo = params.get("out_trade_no");
                    //支付成功，处理业务
                    Orders orders = ordersService.findByOrderNum(outTradeNo);
                    if (orders.getStatus() != 1){
                        log.info("订单回调重复："+orders.toString());
                        return;
                    }
                    SelfOrderRemind r = new SelfOrderRemind();
                    r.setOrdersId(orders.getId());
                    r.setCreateTime(DateUtil.createTime());
                    r.setStatus(1);
                    selfOrdersRemindJpaRepository.save(r);
                    orders.setPayWay(2); //支付方式为2支付宝
                    orders.setStatus(2); //已付款
                    orders.setPayTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); //设置支付时间
                    //5.虚拟商品处理
                    if (orders.getIsExpress() == 2){ //是否需要发货(1需要发货 2无需发货)
                        //虚拟商品发货，发货成功为确认收货，否则不做变化
                        SelfGoodsVirtual v = selfGoodsVirtualService.sendGoods(orders.getGoodsId());
                        if (v != null){
                            orders.setVirtualId(v.getId()); //虚拟商品id
                            orders.setExpressTime(DateUtil.createTime()); //发货时间
                            orders.setFinishTime(DateUtil.createTime()); //收货时间
                            orders.setStatus(4); //确认收货
                            log.info("虚拟商品发货成功，单号："+outTradeNo);
                            System.err.println("虚拟商品发货成功，单号："+outTradeNo);
                            String value = commonRepository.findOne(237).getValue();
                            if("是".equals(value)){
                                //6.用户积分添加
                                String jifenCount = orders.getPayMoney().toString();
                                Long userId = orders.getUserId();
                                userRepository.addOrderJifen(jifenCount, userId);
                                //7.用户积分明细
                                JiFen jiFen = new JiFen();
                                jiFen.setCreateAt(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                                jiFen.setNumber(jifenCount);
                                jiFen.setUserId(userId.toString());
                                jiFen.setContent("自营商城");
                                jiFen.setDes("自营商城积分+"+jifenCount);
                                jiFenService.saveBody(jiFen);
                            }
                        }
                    }
                    ordersService.updateBody(orders);
                    //订单分销
                    ordersService.fenXiao(orders.getId());
                    //公众号消息通知
                    userService.orderPay(orders.getUserId(), orders.getOrderNum(),orders.getPayMoney().toString(),orders.getCreateAt());
                }

            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
            log.info("回调验证失败！！！");
        }
    }


    @ApiOperation("支付宝回调")
    @RequestMapping("/notifyAppZS")
    @Transactional(rollbackFor = Exception.class)
    @IgnoreSecurity
    public void notifyAppZS(HttpServletRequest request, HttpServletResponse response){
        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        //切记alipaypublickey是支付宝的公钥，请去open.alipay.com对应应用下查看。
        //boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
        try {
            log.info("回调成功！！！");
            CommonInfo urls = commonRepository.findOne(200);
            boolean flag = AlipaySignature.rsaCertCheckV1(params,urls.getValue()+"/alipayCertPublicKey_RSA2.crt", AliPayConstants.CHARSET, "RSA2");
            log.info(flag+"回调验证信息");
            if(flag){
                String tradeStatus = params.get("trade_status");
                if("TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus)){
                    String outTradeNo = params.get("out_trade_no");
                    //支付成功，处理业务
                    Orders orders = ordersService.findByOrderNum(outTradeNo);
                    if (orders.getStatus() != 1){
                        log.info("订单回调重复："+orders.toString());
                        return;
                    }
                    SelfOrderRemind r = new SelfOrderRemind();
                    r.setOrdersId(orders.getId());
                    r.setCreateTime(DateUtil.createTime());
                    r.setStatus(1);
                    selfOrdersRemindJpaRepository.save(r);
                    orders.setPayWay(2); //支付方式为2支付宝
                    orders.setStatus(2); //已付款
                    orders.setPayTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); //设置支付时间
                    //5.虚拟商品处理
                    if (orders.getIsExpress() == 2){ //是否需要发货(1需要发货 2无需发货)
                        //虚拟商品发货，发货成功为确认收货，否则不做变化
                        SelfGoodsVirtual v = selfGoodsVirtualService.sendGoods(orders.getGoodsId());
                        if (v != null){
                            orders.setVirtualId(v.getId()); //虚拟商品id
                            orders.setExpressTime(DateUtil.createTime()); //发货时间
                            orders.setFinishTime(DateUtil.createTime()); //收货时间
                            orders.setStatus(4); //确认收货
                            log.info("虚拟商品发货成功，单号："+outTradeNo);
                            System.err.println("虚拟商品发货成功，单号："+outTradeNo);
                            String value = commonRepository.findOne(237).getValue();
                            if("是".equals(value)){
                                //6.用户积分添加
                                String jifenCount = orders.getPayMoney().toString();
                                Long userId = orders.getUserId();
                                userRepository.addOrderJifen(jifenCount, userId);
                                //7.用户积分明细
                                JiFen jiFen = new JiFen();
                                jiFen.setCreateAt(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                                jiFen.setNumber(jifenCount);
                                jiFen.setUserId(userId.toString());
                                jiFen.setContent("自营商城");
                                jiFen.setDes("自营商城积分+"+jifenCount);
                                jiFenService.saveBody(jiFen);
                            }
                        }
                    }
                    ordersService.updateBody(orders);
                    //订单分销
                    ordersService.fenXiao(orders.getId());
                    //公众号消息通知
                    userService.orderPay(orders.getUserId(), orders.getOrderNum(),orders.getPayMoney().toString(),orders.getCreateAt());
                }
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
            log.info("回调验证失败！！！");
        }
    }


    @ApiOperation("支付宝回调")
    @RequestMapping("/notifyAppYunOS")
    @Transactional(rollbackFor = Exception.class)
    @IgnoreSecurity
    public String notifyAppYunOS(HttpServletRequest request, HttpServletResponse response){
        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        String outTradeNo = params.get("outTradeNo");
        String code = params.get("code");
        String key = commonRepository.findOne(169).getValue();
        try {
            boolean flag = PaySignUtil.checkNotifySign(request, key);
            if(flag){
                //支付成功，处理业务
                Orders orders = ordersService.findByOrderNum(outTradeNo);
                if (orders.getStatus() != 1){
                    log.info("订单回调重复："+orders.toString());
                    return "SUCCESS";
                }
                SelfOrderRemind r = new SelfOrderRemind();
                r.setOrdersId(orders.getId());
                r.setCreateTime(DateUtil.createTime());
                r.setStatus(1);
                selfOrdersRemindJpaRepository.save(r);
                orders.setPayWay(2); //支付方式为2支付宝
                orders.setStatus(2); //已付款
                orders.setPayTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); //设置支付时间
                //5.虚拟商品处理
                if (orders.getIsExpress() == 2){ //是否需要发货(1需要发货 2无需发货)
                    //虚拟商品发货，发货成功为确认收货，否则不做变化
                    SelfGoodsVirtual v = selfGoodsVirtualService.sendGoods(orders.getGoodsId());
                    if (v != null){
                        orders.setVirtualId(v.getId()); //虚拟商品id
                        orders.setExpressTime(DateUtil.createTime()); //发货时间
                        orders.setFinishTime(DateUtil.createTime()); //收货时间
                        orders.setStatus(4); //确认收货
                        log.info("虚拟商品发货成功，单号："+outTradeNo);
                        System.err.println("虚拟商品发货成功，单号："+outTradeNo);
                        String value = commonRepository.findOne(237).getValue();
                        if("是".equals(value)){
                            //6.用户积分添加
                            String jifenCount = orders.getPayMoney().toString();
                            Long userId = orders.getUserId();
                            userRepository.addOrderJifen(jifenCount, userId);
                            //7.用户积分明细
                            JiFen jiFen = new JiFen();
                            jiFen.setCreateAt(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                            jiFen.setNumber(jifenCount);
                            jiFen.setUserId(userId.toString());
                            jiFen.setContent("自营商城");
                            jiFen.setDes("自营商城积分+"+jifenCount);
                            jiFenService.saveBody(jiFen);
                        }
                    }
                }
                ordersService.updateBody(orders);
                //订单分销
                ordersService.fenXiao(orders.getId());
                //公众号消息通知
                userService.orderPay(orders.getUserId(), orders.getOrderNum(),orders.getPayMoney().toString(),orders.getCreateAt());
                return "SUCCESS";
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("云购os支付报错！"+e.getMessage());
        }
        return null;
    }



    @IgnoreSecurity
    @RequestMapping("/notifyAppCart")
    @Transactional(rollbackFor = Exception.class)
    public void notifyAppCart(HttpServletRequest request, HttpServletResponse response){
        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        try {
            log.info("回调成功！！！");
            boolean flag = AlipaySignature.rsaCheckV1(params, commonRepository.findOne(64).getValue(), AliPayConstants.CHARSET,"RSA2");
            log.info(flag+"回调验证信息");
            if(flag){
                String tradeStatus = params.get("trade_status");
                if("TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus)){
                    String outTradeNo = params.get("out_trade_no");
                    //支付成功，处理业务
                    List<Orders> list = ordersService.findByPayNum(outTradeNo);
                    for (Orders orders : list) {
                        if (orders.getStatus() != 1){
                            log.info("订单回调重复："+orders.toString());
                            continue;
                        }
                        SelfOrderRemind r = new SelfOrderRemind();
                        r.setOrdersId(orders.getId());
                        r.setCreateTime(DateUtil.createTime());
                        r.setStatus(1);
                        selfOrdersRemindJpaRepository.save(r);
                        orders.setPayWay(2); //支付方式为2支付宝
                        orders.setStatus(2); //已付款
                        orders.setPayTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); //设置支付时间
                        //5.虚拟商品处理
                        if (orders.getIsExpress() == 2){ //是否需要发货(1需要发货 2无需发货)
                            //虚拟商品发货，发货成功为确认收货，否则不做变化
                            SelfGoodsVirtual v = selfGoodsVirtualService.sendGoods(orders.getGoodsId());
                            if (v != null){
                                orders.setVirtualId(v.getId()); //虚拟商品id
                                orders.setExpressTime(DateUtil.createTime()); //发货时间
                                orders.setFinishTime(DateUtil.createTime()); //收货时间
                                orders.setStatus(4); //确认收货
                                log.info("虚拟商品发货成功，单号："+outTradeNo);
                                System.err.println("虚拟商品发货成功，单号："+outTradeNo);
                                String value = commonRepository.findOne(237).getValue();
                                if("是".equals(value)){
                                    //6.用户积分添加
                                    String jifenCount = orders.getPayMoney().toString();
                                    Long userId = orders.getUserId();
                                    userRepository.addOrderJifen(jifenCount, userId);
                                    //7.用户积分明细
                                    JiFen jiFen = new JiFen();
                                    jiFen.setCreateAt(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                                    jiFen.setNumber(jifenCount);
                                    jiFen.setUserId(userId.toString());
                                    jiFen.setContent("自营商城");
                                    jiFen.setDes("自营商城积分+"+jifenCount);
                                    jiFenService.saveBody(jiFen);
                                }
                            }
                        }
                        ordersService.updateBody(orders);
                        //订单分销
                        ordersService.fenXiao(orders.getId());
                        //公众号消息通知
                        userService.orderPay(orders.getUserId(), orders.getOrderNum(),orders.getPayMoney().toString(),orders.getCreateAt());
                    }
                }

            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
            log.info("回调验证失败！！！");
        }
    }


    @ApiOperation("支付宝回调")
    @RequestMapping("/notifyAppZSCart")
    @Transactional(rollbackFor = Exception.class)
    @IgnoreSecurity
    public void notifyAppZSCart(HttpServletRequest request, HttpServletResponse response){
        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        //切记alipaypublickey是支付宝的公钥，请去open.alipay.com对应应用下查看。
        //boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
        try {
            log.info("回调成功！！！");
            CommonInfo urls = commonRepository.findOne(200);
            boolean flag = AlipaySignature.rsaCertCheckV1(params,urls.getValue()+"/alipayCertPublicKey_RSA2.crt", AliPayConstants.CHARSET, "RSA2");
            log.info(flag+"回调验证信息");
            if(flag){
                String tradeStatus = params.get("trade_status");
                if("TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus)){
                    String outTradeNo = params.get("out_trade_no");
                    //支付成功，处理业务
                    List<Orders> list = ordersService.findByPayNum(outTradeNo);
                    for (Orders orders : list) {
                        if (orders.getStatus() != 1){
                            log.info("订单回调重复："+orders.toString());
                            continue;
                        }
                        SelfOrderRemind r = new SelfOrderRemind();
                        r.setOrdersId(orders.getId());
                        r.setCreateTime(DateUtil.createTime());
                        r.setStatus(1);
                        selfOrdersRemindJpaRepository.save(r);
                        orders.setPayWay(2); //支付方式为2支付宝
                        orders.setStatus(2); //已付款
                        orders.setPayTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); //设置支付时间
                        //5.虚拟商品处理
                        if (orders.getIsExpress() == 2){ //是否需要发货(1需要发货 2无需发货)
                            //虚拟商品发货，发货成功为确认收货，否则不做变化
                            SelfGoodsVirtual v = selfGoodsVirtualService.sendGoods(orders.getGoodsId());
                            if (v != null){
                                orders.setVirtualId(v.getId()); //虚拟商品id
                                orders.setExpressTime(DateUtil.createTime()); //发货时间
                                orders.setFinishTime(DateUtil.createTime()); //收货时间
                                orders.setStatus(4); //确认收货
                                log.info("虚拟商品发货成功，单号："+outTradeNo);
                                System.err.println("虚拟商品发货成功，单号："+outTradeNo);
                                String value = commonRepository.findOne(237).getValue();
                                if("是".equals(value)){
                                    //6.用户积分添加
                                    String jifenCount = orders.getPayMoney().toString();
                                    Long userId = orders.getUserId();
                                    userRepository.addOrderJifen(jifenCount, userId);
                                    //7.用户积分明细
                                    JiFen jiFen = new JiFen();
                                    jiFen.setCreateAt(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                                    jiFen.setNumber(jifenCount);
                                    jiFen.setUserId(userId.toString());
                                    jiFen.setContent("自营商城");
                                    jiFen.setDes("自营商城积分+"+jifenCount);
                                    jiFenService.saveBody(jiFen);
                                }
                            }
                        }
                        ordersService.updateBody(orders);
                        //订单分销
                        ordersService.fenXiao(orders.getId());
                        //公众号消息通知
                        userService.orderPay(orders.getUserId(), orders.getOrderNum(),orders.getPayMoney().toString(),orders.getCreateAt());
                    }
                }
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
            log.info("回调验证失败！！！");
        }
    }


    @ApiOperation("支付宝回调")
    @RequestMapping("/notifyAppYunOSCart")
    @Transactional(rollbackFor = Exception.class)
    @IgnoreSecurity
    public String notifyAppYunOSCart(HttpServletRequest request, HttpServletResponse response){
        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        String outTradeNo = params.get("outTradeNo");
        String key = commonRepository.findOne(169).getValue();
        try {
            boolean flag = PaySignUtil.checkNotifySign(request, key);
            if(flag){
                //支付成功，处理业务
                List<Orders> list = ordersService.findByPayNum(outTradeNo);
                for (Orders orders : list) {
                    if (orders.getStatus() != 1){
                        log.info("订单回调重复："+orders.toString());
                        continue;
                    }
                    SelfOrderRemind r = new SelfOrderRemind();
                    r.setOrdersId(orders.getId());
                    r.setCreateTime(DateUtil.createTime());
                    r.setStatus(1);
                    selfOrdersRemindJpaRepository.save(r);
                    orders.setPayWay(2); //支付方式为2支付宝
                    orders.setStatus(2); //已付款
                    orders.setPayTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); //设置支付时间
                    //5.虚拟商品处理
                    if (orders.getIsExpress() == 2){ //是否需要发货(1需要发货 2无需发货)
                        //虚拟商品发货，发货成功为确认收货，否则不做变化
                        SelfGoodsVirtual v = selfGoodsVirtualService.sendGoods(orders.getGoodsId());
                        if (v != null){
                            orders.setVirtualId(v.getId()); //虚拟商品id
                            orders.setExpressTime(DateUtil.createTime()); //发货时间
                            orders.setFinishTime(DateUtil.createTime()); //收货时间
                            orders.setStatus(4); //确认收货
                            log.info("虚拟商品发货成功，单号："+outTradeNo);
                            System.err.println("虚拟商品发货成功，单号："+outTradeNo);
                            String value = commonRepository.findOne(237).getValue();
                            if("是".equals(value)){
                                //6.用户积分添加
                                String jifenCount = orders.getPayMoney().toString();
                                Long userId = orders.getUserId();
                                userRepository.addOrderJifen(jifenCount, userId);
                                //7.用户积分明细
                                JiFen jiFen = new JiFen();
                                jiFen.setCreateAt(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                                jiFen.setNumber(jifenCount);
                                jiFen.setUserId(userId.toString());
                                jiFen.setContent("自营商城");
                                jiFen.setDes("自营商城积分+"+jifenCount);
                                jiFenService.saveBody(jiFen);
                            }
                        }
                    }
                    ordersService.updateBody(orders);
                    //订单分销
                    ordersService.fenXiao(orders.getId());
                    //公众号消息通知
                    userService.orderPay(orders.getUserId(), orders.getOrderNum(),orders.getPayMoney().toString(),orders.getCreateAt());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("云购os支付报错！"+e.getMessage());
        }
        return null;
    }












    @IgnoreSecurity
    @ApiOperation("app支付")
    @GetMapping("/payApp")
    @Transactional(rollbackFor = Exception.class)
    public Result payApp(Long ordersId){
        log.info("开始下单了！！");
        String one2 = commonRepository.findOne(19).getValue();

        String returl=one2+"/pages/zysc/my/payment?id="+ordersId;

        Orders orders = ordersJpaRepository.getOne(ordersId);
        String outTradeNo=orders.getOrderNum();
        //校验金额是否一致
        Goods byId = goodsJpaRepository.findById(orders.getGoodsId()).orElse(null);
        if(byId.getStatus().equals(2)){
            return ResultUtil.error(-200,"商品已经下架了");
        }
        UserInfo userById = userRepository.getUserById(orders.getUserId());
        Double aDouble=0.00;
        SelfGoodsSku selfGoodsSku = selfGoodsSkuJpaRepository.findById(orders.getSkuId()).orElse(null);
        if(StringUtils.isEmpty(userById.getRelationId())){
            aDouble = AmountCalUtils.moneyMul(selfGoodsSku.getSkuPrice(), orders.getNumber());
        }else{
            aDouble = AmountCalUtils.moneyMul(selfGoodsSku.getMemberPrice(), orders.getNumber());
        }
        if(byId.getPostagePrice()!=null){
            aDouble=AmountCalUtils.add(aDouble,byId.getPostagePrice().doubleValue());
        }
        if (orders.getCouponMoney() != null){ //优惠券金额不为空
            aDouble = (BigDecimal.valueOf(aDouble).subtract(orders.getCouponMoney())).doubleValue();
        }
        if(aDouble!=orders.getPayMoney().doubleValue()){
            ordersJpaRepository.deleteById(ordersId);
            return ResultUtil.error(-100,"订单信息错误，请重新下单！");
        }
        String pay = commonRepository.findOne(167).getValue();
        String result="";
        try {
            if("1".equals(pay)){
                String url=one2+"/tao/aliPay/notifyApp";
                log.info("回调地址:"+url);
                //实例化客户端
                AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", commonRepository.findOne(63).getValue(), commonRepository.findOne(65).getValue(), "json", AliPayConstants.CHARSET, commonRepository.findOne(64).getValue(), "RSA2");
                //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
                AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
                //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
                AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
                model.setBody(orders.getTitle());
                model.setSubject(orders.getTitle());
                model.setOutTradeNo(outTradeNo);
                model.setTimeoutExpress("30m");
                model.setTotalAmount(orders.getPayMoney()+""); //金额
                model.setProductCode("QUICK_MSECURITY_PAY");
                request.setBizModel(model);
                request.setNotifyUrl(url);
                request.setReturnUrl(returl);
                AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
                if(response.isSuccess()){
                    result=response.getBody();
                } else {
                    log.info("调用失败");
                }
            }else if("2".equals(pay)){
                String url=one2+"/tao/aliPay/notifyAppYunOS";
                log.info("回调地址:"+url);
                String mchId = commonRepository.findOne(168).getValue();
                String key = commonRepository.findOne(169).getValue();
                result = AliPay.appPay(outTradeNo, orders.getPayMoney()+"", mchId, orders.getTitle(), null, url, null, null, null, null,key);
            }else{
                String url=one2+"/tao/aliPay/notifyAppZS";
                log.info("回调地址:"+url);
                //构造client
                CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
                //设置网关地址
                certAlipayRequest.setServerUrl("https://openapi.alipay.com/gateway.do");
                //设置应用Id
                certAlipayRequest.setAppId(commonRepository.findOne(170).getValue());
                //设置应用私钥
                certAlipayRequest.setPrivateKey(commonRepository.findOne(171).getValue());
                //设置请求格式，固定值json
                certAlipayRequest.setFormat("json");
                //设置字符集
                certAlipayRequest.setCharset(AliPayConstants.CHARSET);
                //设置签名类型
                certAlipayRequest.setSignType(AliPayConstants.SIGNTYPE);
                CommonInfo urls = commonRepository.findOne(200);
                certAlipayRequest.setCertPath(urls.getValue()+"/appCertPublicKey.crt"); //应用公钥证书路径（app_cert_path 文件绝对路径）
                certAlipayRequest.setAlipayPublicCertPath(urls.getValue()+"/alipayCertPublicKey_RSA2.crt"); //支付宝公钥证书文件路径（alipay_cert_path 文件绝对路径）
                certAlipayRequest.setRootCertPath(urls.getValue()+"/alipayRootCert.crt");  //支付宝CA根证书文件路径（alipay_root_cert_path 文件绝对路径）
                //构造client
                AlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);

                //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
                AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
                //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
                AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
                model.setBody(Config.BASE_NAME);
                model.setSubject(Config.BASE_NAME);
                model.setOutTradeNo(outTradeNo);
                model.setTimeoutExpress("30m");
                model.setTotalAmount(orders.getPayMoney()+"");
                model.setProductCode("QUICK_MSECURITY_PAY");
                request.setBizModel(model);
                request.setNotifyUrl(url);
                //这里和普通的接口调用不同，使用的是sdkExecute
                AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
                if(response.isSuccess()){
                    result=response.getBody();
                }else{
                    result=null;
                }
            }
            return ResultUtil.success(result);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return ResultUtil.error(-100,"获取订单失败！");

    }

    @IgnoreSecurity
    @ApiOperation("h5支付")
    @GetMapping(value = "/payH5")
    @Transactional(rollbackFor = Exception.class)
    public Result payH5(Long ordersId) {
        String one2 = commonRepository.findOne(19).getValue();

        String returl = one2+"/pages/zysc/my/payment?id="+ordersId;
        try {
            Orders orders = ordersJpaRepository.getOne(ordersId);
            Goods byId = goodsJpaRepository.findById(orders.getGoodsId()).orElse(null);
            if(byId.getStatus().equals(2)){
                return ResultUtil.error(-200,"商品已经下架了");
            }
            UserInfo userById = userRepository.getUserById(orders.getUserId());
            Double aDouble=0.00;
            SelfGoodsSku selfGoodsSku = selfGoodsSkuJpaRepository.findById(orders.getSkuId()).orElse(null);
            if(StringUtils.isEmpty(userById.getRelationId())){
                aDouble = AmountCalUtils.moneyMul(selfGoodsSku.getSkuPrice(), orders.getNumber());
            }else{
                aDouble = AmountCalUtils.moneyMul(selfGoodsSku.getMemberPrice(), orders.getNumber());
            }
            if(byId.getPostagePrice()!=null){
                aDouble=AmountCalUtils.add(aDouble,byId.getPostagePrice().doubleValue());
            }
            if (orders.getCouponMoney() != null){ //优惠券金额不为空
                aDouble = (BigDecimal.valueOf(aDouble).subtract(orders.getCouponMoney())).doubleValue();
            }
            if(aDouble!=orders.getPayMoney().doubleValue()){
                ordersJpaRepository.deleteById(ordersId);
                return ResultUtil.error(-100,"订单信息错误，请重新下单！");
            }

            String pay = commonRepository.findOne(167).getValue();
            String result="";

            if("1".equals(pay)){
                String url=one2+"/tao/aliPay/notifyApp";
                log.info("回调地址:"+url);
                AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", commonRepository.findOne(63).getValue(), commonRepository.findOne(65).getValue(), "json", AliPayConstants.CHARSET, commonRepository.findOne(64).getValue(), "RSA2");
                AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();
                JSONObject order = new JSONObject();
                order.put("out_trade_no",orders.getOrderNum()); //订单号
                order.put("subject", orders.getTitle()); //商品标题
                order.put("product_code", "QUICK_WAP_WAY");
                order.put("body", orders.getTitle());//商品名称
                order.put("total_amount", orders.getPayMoney()+""); //金额
                alipayRequest.setBizContent(order.toString());
                alipayRequest.setNotifyUrl(url); //在公共参数中设置回跳和通知地址
                alipayRequest.setReturnUrl(returl); //线上通知页面地址
                result = alipayClient.pageExecute(alipayRequest).getBody();
            }else if("2".equals(pay)){
                String url=one2+"/tao/aliPay/notifyAppYunOS";
                log.info("回调地址:"+url);
                String mchId = commonRepository.findOne(168).getValue();
                String key = commonRepository.findOne(169).getValue();
                AliPayH5Biz aliPayH5Biz = AliPay.h5Pay(orders.getOrderNum(), orders.getPayMoney()+"", mchId,orders.getTitle(), null, url, returl, null, null, null,null,key);
                result = aliPayH5Biz.getForm();
            }else{
                String url=one2+"/tao/aliPay/notifyAppZS";
                log.info("回调地址:"+url);
                //构造client
                CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
                //设置网关地址
                certAlipayRequest.setServerUrl("https://openapi.alipay.com/gateway.do");
                //设置应用Id
                certAlipayRequest.setAppId(commonRepository.findOne(170).getValue());
                //设置应用私钥
                certAlipayRequest.setPrivateKey(commonRepository.findOne(171).getValue());
                //设置请求格式，固定值json
                certAlipayRequest.setFormat("json");
                //设置字符集
                certAlipayRequest.setCharset(AliPayConstants.CHARSET);
                //设置签名类型
                certAlipayRequest.setSignType(AliPayConstants.SIGNTYPE);
                CommonInfo urls = commonRepository.findOne(200);
                certAlipayRequest.setCertPath(urls.getValue()+"/appCertPublicKey.crt"); //应用公钥证书路径（app_cert_path 文件绝对路径）
                certAlipayRequest.setAlipayPublicCertPath(urls.getValue()+"/alipayCertPublicKey_RSA2.crt"); //支付宝公钥证书文件路径（alipay_cert_path 文件绝对路径）
                certAlipayRequest.setRootCertPath(urls.getValue()+"/alipayRootCert.crt");  //支付宝CA根证书文件路径（alipay_root_cert_path 文件绝对路径）
                //构造client
                AlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);
                AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();
                JSONObject order = new JSONObject();
                order.put("out_trade_no", orders.getOrderNum()); //订单号
                order.put("subject", orders.getTitle()); //商品标题
                order.put("product_code", "QUICK_WAP_WAY");
                order.put("body", orders.getTitle());//商品名称
                order.put("total_amount", orders.getPayMoney()+""); //金额
                alipayRequest.setBizContent(order.toString());
                alipayRequest.setNotifyUrl(url); //在公共参数中设置回跳和通知地址
                alipayRequest.setReturnUrl(returl); //线上通知页面地址
                result = alipayClient.pageExecute(alipayRequest).getBody();
            }

            return ResultUtil.success(result);
        }catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return ResultUtil.error(-100,"获取订单失败！");
    }


    @IgnoreSecurity
    @ApiOperation("app支付")
    @GetMapping("/payAppCart")
    @Transactional(rollbackFor = Exception.class)
    public Result payAppCart(String payNum,BigDecimal payMoney){
        log.info("开始下单了！！");
        String one2 = commonRepository.findOne(19).getValue();

        String body = Config.BASE_NAME;
        List<Orders> list = ordersService.findByPayNum(payNum);
        if (list.size() >0){
            body = list.get(0).getTitle();
        }
        //支付金额校验
        BigDecimal paySum = new BigDecimal("0.00");
        for (Orders o : list) {
            Goods g = goodsJpaRepository.findById(o.getGoodsId()).orElse(null);
            if(g==null || g.getStatus()!=1){
                return ResultUtil.error(-200, "商品已被下架或移除，请选择其他商品！");
            }
            paySum = paySum.add(o.getPayMoney());
            if (o.getStatus() != 1) {
                return ResultUtil.error(-200, "订单已经支付过了！");
            }
        }
        log.info("支付金额，传入金额："+payMoney+"计算金额："+paySum);
        payMoney = paySum;
        String pay = commonRepository.findOne(167).getValue();
        String result="";
        try {
            if("1".equals(pay)){
                String url=one2+"/tao/aliPay/notifyAppCart";
                log.info("回调地址:"+url);
                //实例化客户端
                AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", commonRepository.findOne(63).getValue(), commonRepository.findOne(65).getValue(), "json", AliPayConstants.CHARSET, commonRepository.findOne(64).getValue(), "RSA2");
                //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
                AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
                //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
                AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
                model.setBody(body);
                model.setSubject(body);
                model.setOutTradeNo(payNum);
                model.setTimeoutExpress("30m");
                model.setTotalAmount(payMoney+""); //金额
                model.setProductCode("QUICK_MSECURITY_PAY");
                request.setBizModel(model);
                request.setNotifyUrl(url);
                request.setReturnUrl(one2);
                AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
                if(response.isSuccess()){
                    result=response.getBody();
                } else {
                    log.info("调用失败");
                }
            }else if("2".equals(pay)){
                String url=one2+"/tao/aliPay/notifyAppYunOSCart";
                log.info("回调地址:"+url);
                String mchId = commonRepository.findOne(168).getValue();
                String key = commonRepository.findOne(169).getValue();
                result = AliPay.appPay(payNum, payMoney+"", mchId, body, null, url, null, null, null, null,key);
            }else{
                String url=one2+"/tao/aliPay/notifyAppZSCart";
                log.info("回调地址:"+url);
                //构造client
                CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
                //设置网关地址
                certAlipayRequest.setServerUrl("https://openapi.alipay.com/gateway.do");
                //设置应用Id
                certAlipayRequest.setAppId(commonRepository.findOne(170).getValue());
                //设置应用私钥
                certAlipayRequest.setPrivateKey(commonRepository.findOne(171).getValue());
                //设置请求格式，固定值json
                certAlipayRequest.setFormat("json");
                //设置字符集
                certAlipayRequest.setCharset(AliPayConstants.CHARSET);
                //设置签名类型
                certAlipayRequest.setSignType(AliPayConstants.SIGNTYPE);
                CommonInfo urls = commonRepository.findOne(200);
                certAlipayRequest.setCertPath(urls.getValue()+"/appCertPublicKey.crt"); //应用公钥证书路径（app_cert_path 文件绝对路径）
                certAlipayRequest.setAlipayPublicCertPath(urls.getValue()+"/alipayCertPublicKey_RSA2.crt"); //支付宝公钥证书文件路径（alipay_cert_path 文件绝对路径）
                certAlipayRequest.setRootCertPath(urls.getValue()+"/alipayRootCert.crt");  //支付宝CA根证书文件路径（alipay_root_cert_path 文件绝对路径）
                //构造client
                AlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);

                //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
                AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
                //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
                AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
                model.setBody(Config.BASE_NAME);
                model.setSubject(Config.BASE_NAME);
                model.setOutTradeNo(payNum);
                model.setTimeoutExpress("30m");
                model.setTotalAmount(payMoney+"");
                model.setProductCode("QUICK_MSECURITY_PAY");
                request.setBizModel(model);
                request.setNotifyUrl(url);
                //这里和普通的接口调用不同，使用的是sdkExecute
                AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
                if(response.isSuccess()){
                    result=response.getBody();
                }else{
                    result=null;
                }
            }
            return ResultUtil.success(result);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return ResultUtil.error(-100,"获取订单失败！");

    }

    @IgnoreSecurity
    @ApiOperation("h5支付")
    @GetMapping(value = "/payH5Cart")
    @Transactional(rollbackFor = Exception.class)
    public Result payH5Cart(String payNum,BigDecimal payMoney) {
        String one2 = commonRepository.findOne(19).getValue();
        try {
            String body = Config.BASE_NAME;
            List<Orders> list = ordersService.findByPayNum(payNum);
            if (list.size() >0){
                body = list.get(0).getTitle();
            }
            //支付金额校验
            BigDecimal paySum = new BigDecimal("0.00");
            for (Orders o : list) {
                Goods g = goodsJpaRepository.findById(o.getGoodsId()).orElse(null);
                if(g==null || g.getStatus()!=1){
                    return ResultUtil.error(-200, "商品已被下架或移除，请选择其他商品！");
                }
                paySum = paySum.add(o.getPayMoney());
                if (o.getStatus() != 1) {
                    return ResultUtil.error(-200, "订单已经支付过了！");
                }
            }
            log.info("支付金额，传入金额："+payMoney+"计算金额："+paySum);
            payMoney = paySum;

            String pay = commonRepository.findOne(167).getValue();
            String result="";

            if("1".equals(pay)){
                String url=one2+"/tao/aliPay/notifyAppCart";
                log.info("回调地址:"+url);
                AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", commonRepository.findOne(63).getValue(), commonRepository.findOne(65).getValue(), "json", AliPayConstants.CHARSET, commonRepository.findOne(64).getValue(), "RSA2");
                AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();
                JSONObject order = new JSONObject();
                order.put("out_trade_no",payNum); //订单号
                order.put("subject", body); //商品标题
                order.put("product_code", "QUICK_WAP_WAY");
                order.put("body", body);//商品名称
                order.put("total_amount", payMoney+""); //金额
                alipayRequest.setBizContent(order.toString());
                alipayRequest.setNotifyUrl(url); //在公共参数中设置回跳和通知地址
                alipayRequest.setReturnUrl(one2); //线上通知页面地址
                result = alipayClient.pageExecute(alipayRequest).getBody();
            }else if("2".equals(pay)){
                String url=one2+"/tao/aliPay/notifyAppYunOSCart";
                log.info("回调地址:"+url);
                String mchId = commonRepository.findOne(168).getValue();
                String key = commonRepository.findOne(169).getValue();
                AliPayH5Biz aliPayH5Biz = AliPay.h5Pay(payNum, payMoney+"", mchId,body, null, url, one2, null, null, null,null,key);
                result = aliPayH5Biz.getForm();
            }else{
                String url=one2+"/tao/aliPay/notifyAppZSCart";
                log.info("回调地址:"+url);
                //构造client
                CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
                //设置网关地址
                certAlipayRequest.setServerUrl("https://openapi.alipay.com/gateway.do");
                //设置应用Id
                certAlipayRequest.setAppId(commonRepository.findOne(170).getValue());
                //设置应用私钥
                certAlipayRequest.setPrivateKey(commonRepository.findOne(171).getValue());
                //设置请求格式，固定值json
                certAlipayRequest.setFormat("json");
                //设置字符集
                certAlipayRequest.setCharset(AliPayConstants.CHARSET);
                //设置签名类型
                certAlipayRequest.setSignType(AliPayConstants.SIGNTYPE);
                CommonInfo urls = commonRepository.findOne(200);
                certAlipayRequest.setCertPath(urls.getValue()+"/appCertPublicKey.crt"); //应用公钥证书路径（app_cert_path 文件绝对路径）
                certAlipayRequest.setAlipayPublicCertPath(urls.getValue()+"/alipayCertPublicKey_RSA2.crt"); //支付宝公钥证书文件路径（alipay_cert_path 文件绝对路径）
                certAlipayRequest.setRootCertPath(urls.getValue()+"/alipayRootCert.crt");  //支付宝CA根证书文件路径（alipay_root_cert_path 文件绝对路径）
                //构造client
                AlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);
                AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();
                JSONObject order = new JSONObject();
                order.put("out_trade_no", payNum); //订单号
                order.put("subject", body); //商品标题
                order.put("product_code", "QUICK_WAP_WAY");
                order.put("body", body);//商品名称
                order.put("total_amount", payMoney+""); //金额
                alipayRequest.setBizContent(order.toString());
                alipayRequest.setNotifyUrl(url); //在公共参数中设置回跳和通知地址
                alipayRequest.setReturnUrl(one2); //线上通知页面地址
                result = alipayClient.pageExecute(alipayRequest).getBody();
            }

            return ResultUtil.success(result);
        }catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return ResultUtil.error(-100,"获取订单失败！");
    }



}
